import { getInfo, login, logout } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Notification } from 'element-ui'
import RsaUtil from '@/utils/rsa-util'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, params) {
    // debugger
    return new Promise((resolve, reject) => {
      login(params.method, params).then(response => {
        const { token, tips } = response
        const data = {
          token: token
        }
        if (tips) {
          Notification.info({ title: '账户异常提示', message: tips, showClose: false })
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        console.log('请求异常', error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 生成一对密钥
      const { publicKey, privateKey } = RsaUtil.generateKeyPair()
      const rsaUtil = new RsaUtil()
      getInfo({ publicKey: publicKey }).then(response => {
        const data = response

        if (!data) {
          return reject('验证失败，请重新登录。')
        }
        data.avatar = `${process.env.VUE_APP_BASE_HOST}/${data.avatar}`
        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

